using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Log;
using GrapeCity.Forguncy.Plugin;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;

namespace PluginRegion
{
    [Icon("pack://application:,,,/PluginRegion;component/Resources/Icon.png")]
    [Designer("PluginRegion.Designer.PluginRegionServerCommandDesigner, PluginRegion")]
    public class PluginRegionServerCommand : Command, ICommandExecutableInServerSideAsync, ISubListCommand, IContainSubCommands
    {
        [Description("同步或异步")]
        [DisplayName("同步或异步")]
        [RadioGroupProperty(ValueList = "同步|异步")]
        public string SyncFlag { get; set; } = "同步";

        [Description("注释的别名")]
        [DisplayName("命令组注释")]
        public string RegionName { get; set; }

        /// <summary>
        /// 子命令
        /// </summary>
        [Browsable(false)]
        public List<Command> CommandList { get; set; } = new List<Command>();

        public IEnumerable<List<Command>> EnumSubCommands()
        {
            yield return CommandList;
        }

        public IServerCommandExecuteContext asyncdataContext;

        public async Task<ExecuteResult> ASyncExecuteAsync(List<Command> commands)
        {
            var result = await asyncdataContext.ExecuteCommandsAsync(commands);
            return new ExecuteResult();
        }

        public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            string syncFlag = SyncFlag;
            if (syncFlag.Equals("同步"))
            {
                dataContext.Log.AppendLine(syncFlag + "子命令组开始执行");
                var result = await dataContext.ExecuteCommandsAsync(CommandList);
                dataContext.Log.AppendLine(syncFlag + "子命令组执行结束");
            } else if (syncFlag.Equals("异步"))
            {
                var commands = CommandList;
                PluginRegionServerCommandSub pluginRegionServerCommandSub = new PluginRegionServerCommandSub(commands);

                dataContext.Log.AppendLine("异步子命令组已启动，后台执行中...");
            } else
            {
                var result = $"未知执行模式：{syncFlag}，命令未执行";
                dataContext.Log.AppendLine(result);
                throw new Exception(result);
            }
            return new ExecuteResult();
        }

        public override string ToString()
        {
            return SyncFlag + "命令组 " + RegionName;
        }

        public override CommandScope GetCommandScope()
        {
            return CommandScope.ExecutableInServer;
        }
    }
}
